﻿namespace In66.Net.Share.Registrar.WebRegistrar
{
    public static partial class ServiceRegistrar
    {
        /// <summary>
        /// 注册跨域组件
        /// </summary>
        public static IServiceCollection AddCors(this IServiceCollection Services, IServiceInfo ServiceInfo)
        {
            Services.AddCors(c =>
            {
                var Cors = Services.BuildServiceProvider().GetService<IOptions<CorsConfig>>().Value;

                if (!Cors.EnableAllIPs)
                {
                    c.AddPolicy(ServiceInfo.CorsPolicy, policy =>
                    {
                        policy.WithOrigins(Cors.IPs.Split(','));
                        policy.AllowAnyHeader();//Ensures that the policy allows any header.
                        policy.AllowAnyMethod();
                        policy.AllowCredentials();
                    });
                }
                else
                {
                    //允许任意跨域请求
                    c.AddPolicy(ServiceInfo.CorsPolicy, policy =>
                    {
                        policy.SetIsOriginAllowed((host) => true)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                    });
                }
            });

            return Services;
        }
    }

}
